package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.config.MyRedissonConfig;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2VO;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MyRedissonConfig redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //2.1)找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                })
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return level1Menus;
    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                //找到子菜单
                .map(CategoryEntity -> {
                    CategoryEntity.setChildren(getChildrens(CategoryEntity, all));
                    return CategoryEntity;
                })
                //菜单排序
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO   1.检查当前删除的菜单，是否被别的地方引用

        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        //反转数组
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    //删除缓存名称category分组下所有缓存
    //@Caching(evict = {
    //        @CacheEvict(value = "category",key = "'1'"),
    //        @CacheEvict(value = "category",key = "'2'")
    //
    //})
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    public List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //其实，这个把add方法放在return上一步，就不用反转数组了，递归的特性嘛
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 获得一级分类
     *
     * @return
     */
    @Cacheable(value = "category",key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("查询数据库...");
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2VO>> getCatalogJson() {
        System.out.println("查询数据库...." + Thread.currentThread().getName());
        //找到所有
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

        //找到一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(categoryEntities, 0L);

        //遍历一级分类
        Map<String, List<Catelog2VO>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {

            //找二级分类
            List<CategoryEntity> level2 = getParent_cid(categoryEntities, level1.getCatId());
            List<Catelog2VO> catelog2VOS = null;
            if (level2 != null) {
                //遍历二级分类
                catelog2VOS = level2.stream().map(l2 -> {
                    //找到三级分类
                    List<CategoryEntity> level3 = getParent_cid(categoryEntities, l2.getCatId());
                    Catelog2VO catelog2VO = new Catelog2VO(level1.getCatId().toString().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<Catelog2VO.Catelog3VO> Catelog3VO = null;
                    if (level3 != null) {
                        //遍历三级分类
                        Catelog3VO = level3.stream().map(l3 -> {
                            return new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                        }).collect(Collectors.toList());

                    }
                    catelog2VO.setCatalog3List(Catelog3VO);
                    return catelog2VO;

                }).collect(Collectors.toList());
            }
            return catelog2VOS;
        }));
        return collect;
    }

    /**
     * 商城首页查询三级分类
     *
     * @return
     */
    //@Override
    public Map<String, List<Catelog2VO>> getCatalogJson2() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String categoryJson = ops.get("categoryJson");
        if (!StringUtils.hasText(categoryJson)) {
            System.out.println("缓存未命中....将要查询数据库...");
            Map<String, List<Catelog2VO>> categoryMap = getCatalogJsonFromDBWithRedissonLock();
            return categoryMap;
        }
        System.out.println("缓存命中....直接返回...");
        Map<String, List<Catelog2VO>> categoryMap = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2VO>>>() {
        });
        return categoryMap;
    }

    public Map<String, List<Catelog2VO>> getCatalogJsonFromDBWithRedissonLock() {
        RLock lock = redisson.redissonClient().getLock("categoryJson-lock");
        lock.lock();
        Map<String, List<Catelog2VO>> dataFromDB=null;
        try {
            dataFromDB = getDataFromDB();
        }finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    private Map<String, List<Catelog2VO>> getDataFromDB() {
        String categoryJson = stringRedisTemplate.opsForValue().get("categoryJson");
        if (StringUtils.hasText(categoryJson)) {
            Map<String, List<Catelog2VO>> categoryMap = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2VO>>>() {
            });
            return categoryMap;
        }
        System.out.println("查询数据库...." + Thread.currentThread().getName());
        //找到所有
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

        //找到一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(categoryEntities, 0L);

        //遍历一级分类
        Map<String, List<Catelog2VO>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {

            //找二级分类
            List<CategoryEntity> level2 = getParent_cid(categoryEntities, level1.getCatId());
            List<Catelog2VO> catelog2VOS = null;
            if (level2 != null) {
                //遍历二级分类
                catelog2VOS = level2.stream().map(l2 -> {
                    //找到三级分类
                    List<CategoryEntity> level3 = getParent_cid(categoryEntities, l2.getCatId());
                    Catelog2VO catelog2VO = new Catelog2VO(level1.getCatId().toString().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<Catelog2VO.Catelog3VO> Catelog3VO = null;
                    if (level3 != null) {
                        //遍历三级分类
                        Catelog3VO = level3.stream().map(l3 -> {
                            return new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                        }).collect(Collectors.toList());

                    }
                    catelog2VO.setCatalog3List(Catelog3VO);
                    return catelog2VO;

                }).collect(Collectors.toList());
            }
            return catelog2VOS;
        }));

        categoryJson = JSON.toJSONString(collect);
        stringRedisTemplate.opsForValue().set("categoryJson", categoryJson, 1, TimeUnit.DAYS);
        return collect;
    }

    public Map<String, List<Catelog2VO>> getCatalogJsonFromDBWithLocalLock() {

        synchronized (this) {
            String categoryJson = stringRedisTemplate.opsForValue().get("categoryJson");
            if (StringUtils.hasText(categoryJson)) {
                Map<String, List<Catelog2VO>> categoryMap = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2VO>>>() {
                });
                return categoryMap;
            }
            System.out.println("查询数据库...." + Thread.currentThread().getName());
            //找到所有
            List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);

            //找到一级分类
            List<CategoryEntity> level1Categorys = getParent_cid(categoryEntities, 0L);

            //遍历一级分类
            Map<String, List<Catelog2VO>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {

                //找二级分类
                List<CategoryEntity> level2 = getParent_cid(categoryEntities, level1.getCatId());
                List<Catelog2VO> catelog2VOS = null;
                if (level2 != null) {
                    //遍历二级分类
                    catelog2VOS = level2.stream().map(l2 -> {
                        //找到三级分类
                        List<CategoryEntity> level3 = getParent_cid(categoryEntities, l2.getCatId());
                        Catelog2VO catelog2VO = new Catelog2VO(level1.getCatId().toString().toString(), null, l2.getCatId().toString(), l2.getName());
                        List<Catelog2VO.Catelog3VO> Catelog3VO = null;
                        if (level3 != null) {
                            //遍历三级分类
                            Catelog3VO = level3.stream().map(l3 -> {
                                return new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                            }).collect(Collectors.toList());

                        }
                        catelog2VO.setCatalog3List(Catelog3VO);
                        return catelog2VO;

                    }).collect(Collectors.toList());
                }
                return catelog2VOS;
            }));

            categoryJson = JSON.toJSONString(collect);
            stringRedisTemplate.opsForValue().set("categoryJson", categoryJson, 1, TimeUnit.DAYS);
            return collect;
        }

    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntities, Long parentId) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid().equals(parentId)).collect(Collectors.toList());
        return collect;
    }
}